<?php
// 应用公共文件

// 成功时调用
use think\response\Json;

if (!function_exists('success')) {
    function success($data): Json
    {
        return json([
            'code' => 0,
            'data' => $data,
        ]);
    }
}
// 失败时调用
if (!function_exists('error')) {
    function error($code, $error): Json
    {
        return json([
            'code' => $code,
            'error' => $error,
        ]);

    }
}

// 随机字符
if (!function_exists('get_rand_str')) {
    function get_rand_str($length)
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        // 打乱字符串
        $randStr = str_shuffle($str);
        return substr($randStr, 0, $length);
    }
}

// 获取客户端IP地址
if (!function_exists('get_client_ip')) {
    function get_client_ip(): ?string
    {
        static $ip = NULL;
        if ($ip !== NULL)
            return $ip;
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
        return $ip;
    }
}
// 二维数组根据键值换为key
if (!function_exists('array_change_key')) {
    function array_change_key ($array, $key): array
    {
        $newArray = [];
        foreach ($array as $k=>$item) {
            $newArray[$item[$key]] = $item;
        }
        return $newArray;
    }
}

// 二维数组根据键值换为key
if (!function_exists('array_group_key')) {
    function array_group_key ($array, $key): array
    {
        $newArray = [];
        foreach ($array as $k=>$item) {
            $newArray[$item[$key]][] = $item;
        }
        return $newArray;
    }
}

// 获取随机默认图片
if (!function_exists('get_random_thumb')) {
    function get_random_thumb ($id): string
    {
        return "/static/image/default/random_" . ($id % 30 + 1) . '.jpg';
    }
}

// 获取目录内的所有图片
if (!function_exists('get_directory_images')) {
    function get_directory_images($directory): array {
        $allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
        $images = array();
        if (is_dir($directory)) {
            if ($handle = opendir($directory)) {
                while (($file = readdir($handle)) !== false) {
                    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($extension, $allowedExtensions)) {
                        $images[] = $directory . '/' . $file;
                    }
                }
                closedir($handle);
            }
        }
        return $images;
    }
}

if (!function_exists('msubstr')) {
    /**
     * 截取字符串
     *
     * @param $str
     * @param int $start
     * @param $length
     * @param string $charset
     * @param bool $suffix
     * @return false|string
     */
    function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
        if(function_exists("mb_substr")){
            $slice= mb_substr($str, $start, $length, $charset);
        }elseif(function_exists('iconv_substr')) {
            $slice= iconv_substr($str,$start,$length,$charset);
        }else{
            $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
            $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
            $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
            $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        $fix='';
        if(strlen($slice) < strlen($str)){
            $fix='...';
        }
        return $suffix ? $slice.$fix : $slice;
    }
}
